<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div>首页</div>
    <script>
        const jsonp=({url,params,callbackName})=>{
            const generateURL=()=>{
                let dataStr='';
                for(let key in params){
                    dataStr+=`${key}=${params[key]}&`
                }
                dataStr+=`callback=${callbackName}`;
                return `${url}?${dataStr}`;
            }
            return new Promise((resolve,reject)=>{
                callbackName=callbackName || 'cb'+Math.random().toString().replace('.','');
                let script=document.createElement('script');
                script.src=generateURL();
                document.body.appendChild(script); // 一定要添加到body中，才会发送请求

                // 会生成一个script标签，src=src；

                window[callbackName]=data=>{
                    resolve(data);
                    document.body.removeChild(script);
                }
            })
        }

        jsonp({
            url:'http://localhost:3000',
            params:{
                name:'格格',
                age:'18'
            },
            callbackName:'getData'
        })
        .then(data=>JSON.parse(data))
        .then(data=>{
            console.log(data);
        })
    </script>
</body>
</html>